<?php

namespace App\Jobs\Train\TrainOrder;

use App\Models\Task\SnapTasks\Repositories\Interfaces\SnapTaskRepositoryInterface;
use App\Models\Train\TrainOrders\TrainOrder;
use App\Models\Trip\OrderPay\OrderPay;
use App\Models\User\AcceleratorPacks\UserAcceleratorPack;
use App\Trip\Orders\TripOrderState;
use App\Trip\Train\Order\Impl\PiaoChiTicketsChangeImpl;
use App\Trip\Train\Order\Impl\PiaoChiTrainBookImpl;
use App\Trip\Train\Order\Impl\PiaoChiTrainSnapImpl;
use App\Trip\Train\Order\Impl\SnapTaskLowLevel\SnapTaskLowLevelImpl;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class ProcessAfterTrainOrderPaid implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private TrainOrder $order;
    private OrderPay   $orderPay;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(TrainOrder $order, OrderPay $orderPay)
    {
        $this->order    = $order;
        $this->orderPay = $orderPay;
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws Exception
     */
    public function handle()
    {
        if ($this->order->isCancel()) {
            Log::info("火车票票支付成功后回调,订单已取消,order_sn:{$this->order->getOrderSn()},out_order_sn:{$this->order->getOutOrderSn()}");
            return;
        }
        $this->handleNormal();
        $this->handleSnap();
    }


    /**
     * @throws Exception
     */
    private function handleNormal()
    {
        $order = $this->order;
        if ($order->isSnapUp()) {
            return;
        }
        switch ($order->getOrderState()) {
            case TripOrderState::ORDER_STATE_PAID:
                $book = new PiaoChiTrainBookImpl($order);
                $book->book();
                break;
            case TripOrderState::ORDER_STATE_CHANGING:
                $change = new PiaoChiTicketsChangeImpl($order);
                $change->change();
                break;
            default:
                //抢票业务在 TrainSnapPaidListener 中处理
                Log::error("订单支付成功：{$order->getOrderSn()}，非已支付或已支付待改签:{$order->getOrderState()}");
        }
    }

    /**
     * @throws Exception
     */
    private function handleSnap()
    {
        $order = $this->order;
        if (!$order->isSnapUp()) {
            return;
        }

        $task_id   = $order->getTaskId();
        $taskRepo  = app(SnapTaskRepositoryInterface::class);
        $task_info = $taskRepo->findOneByTaskId($task_id);
        if (!$task_info) {
            return;
        }

        /**
         * 付费高速抢票中
         **/
        if ($task_info->isPaidHighLevel()) {
            $snap = new PiaoChiTrainSnapImpl($order);
            $snap->snap();
        } else {
            /**
             * 低速抢票并判断 用户是否有 加速包并使用
             **/
            $userAcceleratorPacks = new UserAcceleratorPack();
            $userAcceleratorPacks->usePackBySelfTask($task_info, $order->getUserId());

            /**
             * 开启慢速抢票中
             */
            $snap = new SnapTaskLowLevelImpl($task_id, 'start');
            $snap->start();
        }
    }

    /**
     * 任务的唯一 ID。
     *
     * @return string
     */
    public function uniqueId()
    {
        return $this->order->getOrderSn();
    }

}
